package com.silverhaze.diamond.client.ui.dialogs;

import com.silverhaze.commons.ui.layout.SpringUtilities;
import com.silverhaze.commons.helpers.CommonUIHelper;
import com.silverhaze.diamond.common.entity.Customer;
import com.silverhaze.diamond.common.entity.Service;
import com.silverhaze.diamond.client.data.dao.DAOLocator;
import com.silverhaze.diamond.client.ui.UIStringConstants;
import com.silverhaze.diamond.client.utils.db.ServiceDataSource;

import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


/**
 * Author: Ivan Babanin
 * © Lizard Software, 2007 y.
 */
public class CustomerDialog extends AbstractDialog {
    private boolean edit;
    private Customer customer;
    private DialogType dialogType;

    private JTextField nameField;
    private JTextField surnameField;
    private JTextField patronymicField;
    private JTextField emailField;

    private JTextField organizationField;

    private JRadioButton organizationBtn;
    private JRadioButton personBtn;

    private JTextField telephoneField;

    private JTextArea addressPane;

    private DialogConnector dialogConnector;

    public CustomerDialog(Window owner, Customer c, DialogType dialogType) {
        super(owner);

        initialize(c, dialogType);
    }

    public CustomerDialog(Frame owner, Customer c, DialogType dialogType) {
        super(owner);

        initialize(c, dialogType);
    }

    private void initialize(Customer c, DialogType dialogType) {
        customer = c;
        edit = (c != null);

        this.dialogType = dialogType;

        if (dialogType == DialogType.EDIT) {
            setTitle(UIStringConstants.EDIT_CUSTOMER);
        } else if (dialogType == DialogType.CREATE) {
            setTitle(UIStringConstants.ADD_CUSTOMER);
        } else {
            setTitle("Просмотр покупателя");
        }

        initView(dialogType);
    }

    public CustomerDialog(Window parent, Customer o, DialogType create, DialogConnector dialogConnector) {
        this(parent, o, create);
        this.dialogConnector = dialogConnector;
    }

    protected void init(DialogButtonView viewType) {
        setLayout(new BorderLayout());
    }

    private void initView(DialogType dialogType) {
        JPanel panel = new JPanel(new SpringLayout());

        nameField = createTextField(edit ? customer.getName() : "", 15);
        surnameField = createTextField(edit ? customer.getSurname() : "", 15);
        patronymicField = createTextField(edit ? customer.getPatronymic() : "", 15);
        organizationField = createTextField(edit ? customer.getOrganization() : "", 15);

        emailField = createTextField(edit ? customer.getEmail() : "", 15);
        
        if (dialogType == DialogType.CREATE) {
            ButtonGroup buttonGroup = new ButtonGroup();

            personBtn = new JRadioButton("персона");
            personBtn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    nameField.setEnabled(true);
                    surnameField.setEnabled(true);
                    patronymicField.setEnabled(true);
                    organizationField.setEnabled(false);
                }
            });

            organizationBtn = new JRadioButton("организация");
            organizationBtn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    nameField.setEnabled(false);
                    surnameField.setEnabled(false);
                    patronymicField.setEnabled(false);
                    organizationField.setEnabled(true);
                }
            });

            buttonGroup.add(personBtn);
            buttonGroup.add(organizationBtn);

            panel.add(new JLabel("Тип: "));
            panel.add(CommonUIHelper.createHorizontalBox(personBtn, 2, organizationBtn));

            panel.add(new JLabel(UIStringConstants.NAME + ": "));
            panel.add(nameField);

            panel.add(new JLabel(UIStringConstants.PATRONYMIC + ": "));
            panel.add(patronymicField);

            panel.add(new JLabel(UIStringConstants.SURNAME + ": "));
            panel.add(surnameField);

            panel.add(new JLabel("Организация: "));
            panel.add(organizationField);
        } else {
            if (customer.isBOrganization()) {
                panel.add(new JLabel("Организация: "));
                panel.add(organizationField);
            } else {
                panel.add(new JLabel(UIStringConstants.NAME + ": "));
                panel.add(nameField);

                panel.add(new JLabel(UIStringConstants.PATRONYMIC + ": "));
                panel.add(patronymicField);

                panel.add(new JLabel(UIStringConstants.SURNAME + ": "));
                panel.add(surnameField);
            }
        }

        addressPane = createTextArea(edit ? customer.getAddress() : "", 3, 15);
        addressPane.setLineWrap(true);
        addressPane.setBorder(new LineBorder(Color.BLACK, 1));

        telephoneField = createTextField(edit ? customer.getPhone() : "", 15);

        panel.add(new JLabel(UIStringConstants.PHONE + ": "));
        panel.add(telephoneField);        

        panel.add(new JLabel("Электропочта: "));
        panel.add(emailField);

        panel.add(new JLabel(UIStringConstants.ADDRESS + ": "));
        panel.add(new JScrollPane(addressPane));

        Box hBox = Box.createHorizontalBox();

        final java.util.List<Service> byCustomer = DAOLocator.getInstance().getServices(customer);
        if (customer != null && byCustomer.size() != 0) {
            if (this.dialogType == DialogType.VIEW) {
                hBox.add(new JButton(new AbstractAction("Сервисы покупателя") {
                    public void actionPerformed(ActionEvent e) {
                        SpecificServicesDialog.view(byCustomer, customer);
                    }
                }));
            }
        }

        if (this.dialogType != DialogType.VIEW) {
            hBox.add(new JButton(new AbstractAction(edit ? UIStringConstants.SAVE : UIStringConstants.ADD) {
                public void actionPerformed(ActionEvent e) {
                    okPressed();
                }
            }));
        }

        hBox.add(Box.createHorizontalStrut(2));
        hBox.add(new JButton(new AbstractAction(CustomerDialog.this.dialogType == DialogType.VIEW ?
                "Закрыть" : UIStringConstants.CANCEL) {
            public void actionPerformed(ActionEvent e) {
                cancelPressed();
            }
        }));

        panel.add(new JLabel());
        panel.add(hBox);


        if (dialogType == DialogType.CREATE) {
            SpringUtilities.makeCompactGrid(panel, 9, 2, 10, 10, 10, 10);
            personBtn.setSelected(true);
            organizationField.setEnabled(false);
        } else {
            if (customer.isBOrganization()) {
                organizationField.setCaretPosition(0);
                SpringUtilities.makeCompactGrid(panel, 5, 2, 10, 10, 10, 10);
            } else {
                SpringUtilities.makeCompactGrid(panel, 7, 2, 10, 10, 10, 10);
            }
        }

        add(panel, BorderLayout.CENTER);

        pack();

        setLocationRelativeTo(null);
    }

    protected void okPressed() {
        if (checkFields()) {
            if (edit) {
                if (customer.isBOrganization()) {
                    customer.setOrganization(organizationField.getText().trim());
                } else {
                    customer.setName(nameField.getText().trim());
                    customer.setSurname(surnameField.getText().trim());
                    customer.setPatronymic(patronymicField.getText().trim());
                }

                customer.setAddress(addressPane.getText().trim());
                customer.setPhone(telephoneField.getText().trim());

                ServiceDataSource.getInstance().update(customer);
                ServiceDataSource.getInstance().fireDataSourceChanged(Service.class);
            } else {

                Customer c = new Customer();

                if (organizationBtn.isSelected()) {
                    c.setBOrganization(true);
                    c.setOrganization(organizationField.getText().trim());
                } else {
                    c.setName(nameField.getText().trim());
                    c.setSurname(surnameField.getText().trim());
                    c.setPatronymic(patronymicField.getText().trim());
                }

                c.setAddress(addressPane.getText().trim());
                c.setPhone(telephoneField.getText().trim());

                DAOLocator.getInstance().add(c);

                if (dialogConnector != null) {
                    dialogConnector.objectSelected(c);
                }
            }

            dispose();
        } else {
            Dialogs.showErrorDialog(null, UIStringConstants.PLEASE_FILL_FIELDS);
        }
    }

    private boolean checkFields() {
        boolean result = false;

        if (edit) {
            if (customer.isBOrganization()) {
                result = !organizationField.getText().trim().equals("");
            } else {
                result = !nameField.getText().trim().equals("") &&
                        !surnameField.getText().trim().equals("") &&
                        !patronymicField.getText().trim().equals("");
            }
        } else {
            result = personBtn.isSelected() ? !nameField.getText().trim().equals("") &&
                    !surnameField.getText().trim().equals("") &&
                    !patronymicField.getText().trim().equals("") :
                    !organizationField.getText().trim().equals("");
        }

        result &= !telephoneField.getText().trim().equals("") &&
                !addressPane.getText().trim().equals("");

        return result;
    }

    protected void cancelPressed() {
        dispose();
    }

    public static void createCustomer(Frame parent) {
        CustomerDialog customerDlg = new CustomerDialog(parent, null, DialogType.CREATE);
        customerDlg.setVisible(true);
    }

    public static void editCustomer(Frame parent, Customer c) {
        CustomerDialog customerDlg = new CustomerDialog(parent, c, DialogType.EDIT);
        customerDlg.setVisible(true);
    }

    public static void viewCustomer(Frame parent, Customer c) {
        CustomerDialog customerDlg = new CustomerDialog(parent, c, DialogType.VIEW);
        customerDlg.enableInput(false);
        customerDlg.setVisible(true);
    }

    public static void createCustomer(Window parent, DialogConnector dialogConnector) {
        CustomerDialog customerDlg = new CustomerDialog(parent, null, DialogType.CREATE, dialogConnector);
        customerDlg.setVisible(true);
    }

    public static void createClone(Frame parent, Customer selectedCustomer) {
        CustomerDialog customerDlg = new CustomerDialog(parent, null, DialogType.CREATE);
        customerDlg.initializeFieldsWith(selectedCustomer);
        customerDlg.setVisible(true);
    }

    private void initializeFieldsWith(Customer selectedCustomer) {
        addressPane.setText(selectedCustomer.getAddress());
        telephoneField.setText(selectedCustomer.getPhone());

        if (selectedCustomer.isBOrganization()) {
            organizationBtn.setSelected(true);
            organizationField.setText(selectedCustomer.getOrganization());
        } else {
            personBtn.setSelected(true);
            nameField.setText(selectedCustomer.getName());
            patronymicField.setText(selectedCustomer.getPatronymic());
            surnameField.setText(selectedCustomer.getSurname());
        }
    }
}

